import { createRouter, createWebHistory } from 'vue-router'

/* import Home from '../views/Home.vue'
import About from '../views/About.vue' */

// 创建一个路由, 映射关系
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      component: () =>
        import(/* webpackChunkName: 'home' */ '../views/Home.vue'),
      name: 'home',
      // 自定义属性
      meta: {
        name: 'why',
      },
    },
    {
      path: '/about',
      component: () =>
        import(/* webpackChunkName: 'about' */ '../views/About.vue'),
      name: 'about',
    },
    {
      path: '/order',
      component: () =>
        import(/* webpackChunkName: 'about' */ '../views/Order.vue'),
      name: 'order',
    },
    {
      path: '/user/:id?',
      component: () =>
        import(/* webpackChunkName: 'user' */ '../views/User.vue'),
      name: 'user',
    },
    {
      path: '/login',
      component: () =>
        import(/* webpackChunkName: 'login' */ '../views/Login.vue'),
      name: 'login',
    },
    {
      path: '/:pathMatch(.*)*',
      component: () =>
        import(/* webpackChunkName: 'NotFound' */ '../views/NotFound.vue'),
      name: 'NotFound',
    },
  ],
})

const isAdmin = true
if (isAdmin) {
  router.addRoute({
    path: '/admin',
    component: () =>
      import(/* webpackChunkName: 'admin' */ '../views/Admin.vue'),
  })

  // 添加vip
  router.addRoute('home', {
    path: 'homeVip',
    component: () =>
      import(/* webpackChunkName: 'homeVip' */ '../views/HomeVip.vue'),
  })
}

// 路由守卫
// 进行任何的路由跳转之前, 传入的beforeEach中的函数都会被回调
router.beforeEach((to) => {
  /* if (to.path !== '/login') {
		// 返回导航字符串, 会直接跳转到该导航
		return '/login'
	} */

  const token = localStorage.getItem('token')
  if (to.path === '/order' && !token) {
    return '/login'
  }
})

// 获取所有路由的映射
console.log(router.getRoutes())

export default router
